package com.qiguliuxing.dts.db.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiguliuxing.dts.db.dao.DtsAdMapper;
import com.qiguliuxing.dts.db.domain.DtsAd;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DtsAdService {
	@Resource
	private DtsAdMapper adMapper;

	public List<DtsAd> queryIndex() {
		QueryWrapper<DtsAd> wrapper = new QueryWrapper<>();
		wrapper.eq("position", 1);
		wrapper.eq("deleted", false);
		wrapper.eq("enabled", true);
		return adMapper.selectList(wrapper);
	}

	public List<DtsAd> querySelective(String name, String content, Integer page, Integer limit, String sort,
			String order) {
		QueryWrapper<DtsAd> wrapper = new QueryWrapper<>();
		if (StrUtil.isNotEmpty(name)) {
			wrapper.like("name", name);
		}
		if (StrUtil.isNotEmpty(content)) {
			wrapper.like("content", content);
		}
		wrapper.eq("deleted", false);
		if (StrUtil.isNotEmpty(sort) && StrUtil.isNotEmpty(order)){
			wrapper.orderByDesc(sort);
		}
		Page<DtsAd> iPage = new Page<>(page, limit);
		iPage = adMapper.selectPage(iPage, wrapper);
		return iPage.getRecords();
	}

	public int updateById(DtsAd ad) {
		ad.setUpdateTime(LocalDateTime.now());
		return adMapper.updateById(ad);
	}

	public void deleteById(Integer id) {
		adMapper.deleteById(id);
	}

	public void add(DtsAd ad) {
		ad.setAddTime(LocalDateTime.now());
		ad.setUpdateTime(LocalDateTime.now());
		adMapper.insert(ad);
	}

	public DtsAd findById(Integer id) {
		return adMapper.selectById(id);
	}
}
